#pragma once

#include <string>
#include <iostream>
#include <unordered_map>
#include <utility>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

namespace user {
    using namespace std;

    class User {
    private:
        friend class OnlineUser;

    private:
        string _ip;
        uint16_t _port;

    public:
        User(const string& ip, const uint16_t& port)
            : _ip(ip)
            , _port(port)
        {}
    };

    class OnlineUser {
    private:
        unordered_map<string, User> _users;

    public:
        OnlineUser() = default;

    public:
        void addUser(const string& ip, const uint16_t& port) {
            string id = ip + " - " + to_string(port);
            _users.insert(make_pair(id, User(ip, port)));
        }

        void removeUser(const string& ip, const uint16_t& port) {
            string id = ip + " - " + to_string(port);
            _users.erase(id);
        }

        bool isOnline(const string& ip, const uint16_t& port) {
            string id = ip + " - " + to_string(port);
            return _users.find(id) != _users.end();
        }

        void broadcastMessage(int sockfd,  const string& ip, const uint16_t& port, string& message) {
            for (auto& user : _users) {
                struct sockaddr_in client;
                bzero(&client, sizeof client);

                client.sin_family = AF_INET;
                client.sin_port = htons(user.second._port);
                client.sin_addr.s_addr = inet_addr(user.second._ip.c_str());

                message = ip + " - " + to_string(port) + " # " + message;
                sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&client, sizeof(client));
            }
        }
    };
}